﻿using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using OA.Bll.Authority;
using OA.Model;

namespace OA.Web.Handler
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class InitMenuHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        private DataTable _moduleTable;
        private static DataSet _modules;
        public void ProcessRequest(HttpContext context)
        {
            string strmsg = "";
            bool bl;
            object o = HttpContext.Current.Session["USER"];
            if (o != null)
            {
                try
                {
                    ModulesPresenter bll = new ModulesPresenter();
                    _moduleTable = bll.GetModuleTypeList("").Tables[0];  //取得所有数据得到DataTable 
                    _modules = bll.GetModuleList("");// 取得所有的模块信息列表
                    LoadNode("0");
                    bl = true;
                }
                catch (Exception ex)
                {
                    Log.Logger.LogError(ex.Message);
                    strmsg = ex.Message;
                    bl = false;
                    HttpContext.Current.Response.Write("{ \"flag\":\"" + bl.ToString(CultureInfo.InvariantCulture) +
                                            "\",\"msg\":\"" + strmsg + "\"}");
                }
            }
            else
            {
                strmsg = "用户未登陆!";
                bl = false;
                HttpContext.Current.Response.Write("{ \"flag\":\"" + bl.ToString(CultureInfo.InvariantCulture) +
                                            "\",\"msg\":\"" + strmsg + "\"}");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 递归菜单（模块列表）
        /// </summary>
        /// <param name="mtId">子菜单上级ID</param>
        protected void LoadNode(string mtId)
        {
            StringBuilder str = new StringBuilder();
            DataView dvList = new DataView(_moduleTable);
            dvList.RowFilter = "ModuleTypeSuperiorID=" + mtId; //过滤父节点 

            str.Append(" {\"menus\":[");
            int index=0;
              //for (DataRowView dv in dvList)
            for (int i = 0; i < dvList .Count; i++)
            {
                index++;
                DataRowView dv = dvList[i];
                //判定分类所属的模块是否有浏览权限，无浏览权限，就隐藏此分类
                if (IsAuthority(dv["ModuleTypeID"].ToString()))
                {
                  
                    str.Append("{\"menuid\":\"" + index.ToString(CultureInfo.InvariantCulture) +
                               "\",\"icon\":\"icon-sys\",\"menuname\":\"" + dv["ModuleTypeName"] +
                               "\",\"menus\":[");
                    #region  增加子模块分类
                    ModulesPresenter bll = new ModulesPresenter();
                    DataSet module = bll.GetModuleList("ModuleTypeID=" + dv["ModuleTypeID"]);
                    for (int k = 0; k < module.Tables[0].Rows.Count; k++)
                    {
                        index++;
                        DataRow childDr = module.Tables[0].Rows[k];
                        if (IsShowModule(childDr["ModuleTag"].ToString()))
                        {
                            if ((SessionBox.GetUserSession().Status > 0
                                 || (childDr["ModuleDisabled"].ToString().ToLower() == "true"))
                                && childDr["IsMenu"].ToString().ToLower() == "true")
                            {
                                if (k != module.Tables[0].Rows.Count - 1)
                                {
                                    str.Append("{\"menuid\":\"13\",\"menuname\":\"" + childDr["ModuleName"] +
                                               "\",\"icon\":\"icon-users\",\"url\":\"" + childDr["ModuleURL"] + "?Title=" + childDr["ModuleName"] +
                                               "\"},");
                                }
                                else
                                {
                                    if (str.ToString().Substring(str.Length - 1, 1) != ",")
                                        str.Append(",");
                                    str.Append("{\"menuid\":\"" + index.ToString(CultureInfo.InvariantCulture) + "\",\"menuname\":\"" +
                                               childDr["ModuleName"] + "\",\"icon\":\"icon-users\",\"url\":\"" +
                                               childDr["ModuleURL"] + "?Title=" + childDr["ModuleName"] + "\"}");
                                    //bl = true;
                                }
                            }
                        }
                    }
                    #endregion
                    if (str.ToString().Substring(str.Length - 1, 1) == ",")
                        str.Remove(str.Length - 1, 1);
                    str.Append(i != dvList.Table.Rows.Count - 1 ? "]}," : "]}");
                }
            }
            if (str.ToString().Substring(str.Length - 1, 1) == ",")
                str.Remove(str.Length - 1, 1);
            str.Append("]}");
            HttpContext.Current.Response.Write(str.ToString());
        }









        /// <summary>
        /// 判定分类下属模块是否都有浏览权限
        /// </summary>
        /// <returns></returns>
        public bool IsAuthority(string moduleTypeId)
        {
            ModulesPresenter bll = new ModulesPresenter();
            if (_modules == null)
                _modules = bll.GetModuleList("");
            DataRow[] module = _modules.Tables[0].Select("ModuleTypeID=" + moduleTypeId);
            if(module.Count()==0)
                return true;
            foreach (DataRow row in module)
            {
                string moduleTag = row["ModuleTag"].ToString();
                UserHandle.InitModule(moduleTag);
                if (UserHandle.ValidationHandle(RGP_Tag.Browse))
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 模块是否有浏览权限
        /// </summary>
        /// <returns></returns>
        public bool IsShowModule(string moduleTag)
        {
            bool bl = false;
            UserHandle.InitModule(moduleTag);
            if (UserHandle.ValidationHandle(RGP_Tag.Browse))
                bl = true;
            return bl;
        }
    }
}
